<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
    >
      <!-- 科目下拉框 -->
      <el-form-item label="科目:" prop="subjectId">
        <el-select
          v-model="queryParams.subjectId"
          placeholder="请选择科目"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in xiala"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <!-- 输入知识点编码 -->
      <el-form-item label="知识点编码:" prop="knowledgeCode">
        <el-input
          v-model="queryParams.knowledgeCode"
          placeholder="请输入知识点编码"
          onkeyup="value=value.replace(/[^\w]/g,'')"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 知识点输入框 -->
      <el-form-item label="知识点:" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入知识点"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 新增修改 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:info:add']"
          >新增</el-button
        >
      </el-col>
      <!-- ********************************************* -->
      <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['system:user:import']"
              >excel导入</el-button
            >
          </el-col>
      <!-- ********************************************* -->

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table
      v-loading="loading"
      :data="menuList"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        prop="name"
        label="章节知识点"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column label="编码" align="center" prop="knowledgeCode" width="160" />
      <el-table-column label="类型" align="center" prop="type" width="160">
        <template slot-scope="scope">
          <span v-if="scope.row.type == '1'">章</span>
          <span v-if="scope.row.type == '2'">节</span>
          <span v-if="scope.row.type == '3'">知识点</span>
        </template>
      </el-table-column>
      <el-table-column label="重要性" align="center" prop="importance" width="160">
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.status == 1">启用</span>
          <span v-else-if="scope.row.status == 0">禁用</span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width" width="300"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:info:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:info:add']"
            v-if="scope.row.type != 3"
            >新增</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:info:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="460px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <!-- 科目下拉框 -->
          <el-form-item label="科目名称" prop="subjectId">
            <el-select
              v-model="form.subjectId"
              :disabled="this.disabled"
              placeholder="请选择"
            >
              <el-option
                v-for="item in subjectsnamelist"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-col :span="24"> </el-col>
          <!-- 类型下拉框 -->
          <el-form-item label="类型" prop="type">
            <el-select
              v-model="form.type"
              disabled
              placeholder="请选择"
              ref="gain"
            >
              <el-option
                v-for="item in typelist"
                :key="item.type"
                :label="item.name"
                :value="item.type"
              />
            </el-select>
          </el-form-item>
          <!-- 重要性下拉框 -->
          <el-form-item label="重要性" prop="importanceId">
            <el-select v-model="form.importanceId" placeholder="请选择">
              <el-option
                v-for="item in importance"
                :key="item.importanceId"
                :label="item.name"
                :value="item.importanceId"
              />
            </el-select>
          </el-form-item>
          <el-col :span="18">
            <el-form-item label="编码" prop="knowledgeCode">
              <el-input
                onkeyup="value=value.replace(/[^\w]/g,'')"
                v-model="form.knowledgeCode"
                maxlength="80"
                placeholder="请输入编码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24"> </el-col>
          <el-col :span="18">
            <el-form-item label="名称" prop="name">
              <el-input
                v-model="form.name"
                maxlength="80"
                placeholder="请输入名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24"> </el-col>
          <el-col :span="24">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- ************************************************ -->
    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          > -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- ************************************************ -->
  </div>
</template>

<script>
import {
  canSubjects,
  SubjectsName,
  listMenu,
  getMenu,
  addInfo,
  delInfo,
  updateInfo,
  getInfo,
  delMenu,
  addMenu,
  updateMenu,
} from "@/api/system/outline";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";

// ************************************************
import { getToken } from "@/utils/auth";
// ************************************************

export default {
  name: "Menu",
  components: { Treeselect, IconSelect },
  data() {
    return {
      // ***************************************
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData",
      },
      // ***************************************
      //重要性下拉
      importance: [
        {
          importanceId: 1,
          name: "了解",
        },
        {
          importanceId: 2,
          name: "熟悉",
        },
        {
          importanceId: 3,
          name: "掌握",
        },
      ],
      // 点击新增 考试名称下拉内容
      subjectsnamelist: [],
      // 可用科目下拉列表
      //考试类型下拉
      typelist: [
        {
          name: "章",
          type: 1,
        },
        {
          name: "节",
          type: 2,
        },
        {
          name: "知识点",
          type: 3,
        },
      ],
      xiala: [],
      id: [],
      kaolist: [],
      // 设置状态是否隐藏显示
      state: true,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 菜单表格树数据
      menuList: [],
      //测试测试测试
      // menuList2: [],
      // 菜单树选项
      menuOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      disabled: false,
      // 显示状态数据字典
      visibleOptions: [],
      // 菜单状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        // pageNum: 1,
        // pageSize: 10,
        menuName: null,
        visible: null,
        subjectId:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        subjectsNameId: [
          { required: true, message: "请选择科目名称", trigger: "change" },
        ],
        menuName: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" },
        ],
        knowledgeCode: [
          { required: true, message: "编码不能为空", trigger: "blur" },
        ],
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        importance: [
          { required: true, message: "请选择重要性", trigger: "blur" },
        ],
        type: [{ required: true, message: "选择重要性", trigger: "blur" }],
        subjectId: [
          { required: true, message: "请选择科目名称", trigger: "blur" },
        ],
        importanceId: [
          { required: true, message: "请选择重要性", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.xialaList();
    this.subjectsNameList();
  },
  methods: {
    // ************************************************
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert('导入成功', "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // ************************************************




    /** 查询菜单列表 */
    getList() {
      this.loading = true;
      listMenu(this.queryParams).then((response) => {
        this.menuList = this.handleTree(response.rows, "id");
        this.loading = false;
        console.log("菜单表格树数据", this.menuList);
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.menuName,
        children: node.children,
      };
    },
    // 新增-科目名称-下拉
    subjectsNameList() {
      this.loading = true;
      SubjectsName().then((response) => {
        this.subjectsnamelist = response.rows;
        this.loading = false;
      });
    },
    // 筛选框-科目-下拉
    xialaList() {
      this.loading = true;
      canSubjects().then((response) => {
        this.xiala = response.rows;
        // this.queryParams.subjectId = this.xiala[0].id
        this.loading = false;
      });
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      listMenu().then((response) => {
        this.menuOptions = [];
        const menu = { id: 0, menuName: "主类目", children: [] };
        menu.children = this.handleTree(response.data, "Id");
        this.menuOptions.push(menu);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        subjectId: null,
        parentId: 0,
        menuName: null,
        isFrame: "1",
        isCache: "0",
        visible: "0",
        status: "0",
        type: 1,
        knowledgeCode:'',
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.queryParams.subjectId = this.xiala[0].id
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.disabled = false;
      this.form.subjectId = row.subjectId;
      this.reset();
      if (row.type == "click") {
        this.disabled = false;
        this.form.type = 1;
        this.form.parentId = 0;
      } else if (row.type == "1") {
        let id = row.id;
        getInfo(id).then((response) => {
          this.form.subjectId = response.data.subjectId;
          this.open = true;
        });
        this.disabled = true;
        this.form.type = 2;
        this.form.parentId = row.id;
        this.form.knowledgeCode = row.knowledgeCode
      } else if (row.type == "2") {
        let id = row.id;
        getInfo(id).then((response) => {
          this.form.subjectId = response.data.subjectId;
          this.open = true;
        });
        this.disabled = true;
        this.form.type = 3;
        this.form.parentId = row.id;
        this.form.knowledgeCode = row.knowledgeCode
      }
      this.open = true;
      this.title = "添加大纲";
      this.form.status = 1;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.disabled = true;
      if (row.type == "1") {
        this.disabled = true;
        this.state = true;
      } else if (row.type == "2") {
        this.disabled = true;
        this.state = true;
      } else if (row.type == "3") {
        this.disabled = true;
        this.state = false;
      }
      let id = row.id;
      getInfo(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改大纲";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      console.log(this.form,'提交')
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            this.$confirm('是否确认修改数据？', "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }).then(()=> {
                updateInfo(this.form).then((response) => {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                });
              }).catch(() => {});
            
          } else {
            this.$confirm('是否确认新增数据？', "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }).then(()=> {
                addInfo(this.form).then((response) => {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                });
              }).catch(() => {});
            
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(row,'row')
      if(row.knowledgeCode == '01' || row.knowledgeCode == '0101' || row.knowledgeCode == '0101'){
        this.$confirm("已经出题的知识点不能删除!", "警告", {
        confirmButtonText: "确定",
        type: "warning",
      }).catch(() => {});
      }else{
        this.$confirm("是否确认删除当前数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delInfo(row.id);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
      }
      
    },
  },
};
</script>